/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.apilist;

import java.io.Serializable;

/**
 * 远程调用返回封装类
 * <p>yhao架构中，RequestResult是门面web和微服务间数据传递的关键
 *
 * @author yoara
 */
public class RequestResult<T> implements Serializable {
    private boolean success = true;
    private T body;
    private String errMessage;
    private String errCode;
    //其他可携带的信息
    private String msgBody;
    public RequestResult() {

    }

    public RequestResult(T body) {
        this.body = body;
    }

    public static <T> RequestResult<T> ok(T body){
        return new RequestResult<>(body);
    }

    public RequestResult(boolean success, T body) {
        this.success = success;
        this.body = body;
    }

    public RequestResult(boolean success, T body, String errMessage) {
        this.success = success;
        this.body = body;
        this.errMessage = errMessage;
    }

    public RequestResult(boolean success, T body, String errMessage, String errCode) {
        this.success = success;
        this.body = body;
        this.errMessage = errMessage;
        this.errCode = errCode;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T pickBody() {
        if(!success){
            RequestResultException rre = new RequestResultException(errMessage);
            rre.setMsgBody(msgBody);
            if(errCode!=null){
                rre.setCode(errCode);
            }
            throw rre;
        }
        return body;
    }

    public T getBody() {
        return body;
    }

    public void setBody(T body) {
        this.body = body;
    }

    public String getErrMessage() {
        return errMessage;
    }

    public void setErrMessage(String errMessage) {
        this.errMessage = errMessage;
    }

    public String getErrCode() {
        return errCode;
    }

    public void setErrCode(String errCode) {
        this.errCode = errCode;
    }

    public String getMsgBody() {
        return msgBody;
    }

    public RequestResult<T> setMsgBody(String msgBody) {
        this.msgBody = msgBody;
        return this;
    }
}
